package cn.life.common.support.handler;

import cn.life.common.entity.model.CMessage;
import cn.life.common.entity.model.CMessageCode;
import cn.life.common.support.exception.CException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Description:    管理异常
 *
 * @Author 李佳明
 * @Date 2018/6/24 0024 12:58
 */
@ControllerAdvice
public class CExceptionHandler {

    /**
     * 方法参数无效异常
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public CMessage exceptionHandler(MethodArgumentNotValidException ex) {
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        if (errors.size() > 0) {
            return CMessage.fail(CMessageCode.PARAMS_ERROR, errors.get(0).getDefaultMessage());
        }
        return CMessage.fail(CMessageCode.PARAMS_ERROR, "参数异常");
    }

    /**
     * 自定义参数校验
     */
    @ExceptionHandler({CException.class})
    @ResponseBody
    public CMessage exceptionHandler(CException ex) {
        return CMessage.fail(ex.getCode(), ex.getMessage());
    }

    /**
     * 消息不可读异常
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    @ResponseBody
    public CMessage exceptionHandler(HttpMessageNotReadableException ex) {
        return CMessage.fail(CMessageCode.PARAMS_ERROR, "参数不能为空");
    }

    /**
     * 媒体类型不支持异常
     */
    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    @ResponseBody
    public CMessage exceptionHandler(HttpMediaTypeNotSupportedException ex) {
        return CMessage.fail(CMessageCode.PARAMS_ERROR, "Content type 无效");
    }

    /**
     * 请求方法不支持异常
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    @ResponseBody
    public CMessage exceptionHandler(HttpRequestMethodNotSupportedException ex) {
        return CMessage.fail(CMessageCode.FAIL, ex.getMessage());
    }

    /**
     * 异常
     */
    @ExceptionHandler({Exception.class})
    @ResponseBody
    public CMessage exceptionHandler(Exception ex) {
        ex.printStackTrace();
        return CMessage.fail(CMessageCode.FAIL, "服务器异常");
    }

}